package com.leyou.gateway.filters;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private FilterProperties filterProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if(ifAllowRequest(request)){
            return chain.filter(exchange);
        }
        HttpCookie cookie = request.getCookies().getFirst(jwtProperties.getUser().getCookieName());
        try {
            if(cookie != null){
                Payload<UserInfo> payload = JwtUtils.getInfoFromToken(cookie.getValue(), jwtProperties.getPublicKey(), UserInfo.class);
                // 解析没有问题，证明已经登录
                UserInfo user = payload.getUserInfo();
                String role = user.getRole();
                String username = user.getUsername();
                String method = request.getMethodValue();
                String path = request.getURI().getPath();
                log.info("【网关服务】用户{},角色{}。访问服务{} : {}，", username, role, method, path);
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }

    //配置白名单
    private boolean ifAllowRequest(ServerHttpRequest request) {
        String path = request.getURI().getPath();
        List<String> allowPaths = filterProperties.getAllowPaths();
        for (String allowPath : allowPaths) {
            if(path.startsWith(allowPath)){
                return true;
            }
        }
        return false;
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
